<!DOCTYPE HTML>
<html>
<head>
<title>KPI COMPONENT</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="Stylesheet" type="text/css" href="../../css/common/bi_app_style.css" />
<link rel="Stylesheet" type="text/css" href="../../<%=theme%>/css/theme_style.css" />

<script type="text/JavaScript" src="../../api/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="../../api/js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/JavaScript" src="../../api/js/AnyChart.js"></script>
<script type="text/JavaScript" src="../../api/js/AnyChartHTML5.js"></script>
<script type='text/JavaScript' src='../../../zbw_reporting/scripts/framework_include.js'></script>
<script>
    jQuery(function () { document.documentElement.focus(); });
</script>

<!-- [REQUIRED] SCRIPT FOR INTEGRATION WITH BOI -->
<script type="text/javascript">
    var BOI = parent.BOI; //REQUIRED
    var BOIData = parent.BOIData; //REQUIRED
    var properties = { //REQUIRED
        data: undefined,
        kpi: undefined,
        type: 'Line',
        location: 0,
        drill: '#',
        value: 35 //gauge value
    };
    var initialize = function initialize() {//REQUIRED //initialization function ... see below..
        /*---- begin your component custom initialization code ----*/
        //set property values to dom elements if needed
        refreshProperties();
    };
    var refresh = function refresh() { //REQUIRED function to be called by parent at anytime to refresh data.
    };
    var refreshProperties = function refreshProperties() { //REQUIRED function to be called by parent when a property change occurs
        if (properties.data && properties.kpi) {
            $('#url').attr("href", properties.drill);
            transformXML();
        }
    };
</script>
<!-- COMPONENT SCRIPT -->
<script type="text/javascript">
var chart;
$(document).ready(function () {
    AnyChart.renderingType = anychart.RenderingType.SVG_ONLY //for html5
    chart = new AnyChart();

    //chart = new AnyChart('api/swf/Anychart.swf');
    chart.width = '100%';
    chart.height = '100%';
    //chart.setXMLFile('sample_data/sample_anychart.xml');
    //chart.write('chart_placeholder');
});

function transformXML() {

    var table_data = [];

    var data = properties.data;
    var kpi = properties.kpi;

    var series_set = {};
    var x_axis = kpi.X_AXIS;
    var y_axis = "";
    var s_axis = kpi.SERIES_AXIS;
    var y_caption = "";
    var x_axis_title = '';

    // ANSAJ:: check if data is an DOM object or XML string
    if(data){
        if(data.xml){
            data = data.xml;
        }
    }
    for (var i in kpi.Y_AXES) {
        y_axis = kpi.Y_AXES[i];

        $(data).find('META ZBW_QUERY_OUTPUT_METADATA').each(function () {
            var elem = $(this).find('ELEM').text();
            var fieldname = $(this).find('FIELDNAME').clone()    //clone the element
                    .children() //select all the children
                    .remove()   //remove all the children
                    .end()  //again go back to selected element
                    .text();

            if(fieldname == x_axis)
                x_axis_title = $(this).find('SCRTEXT_L').text();

            if ($(this).attr('type') == 'KF') {
                if (y_axis == elem) {
                    y_axis = fieldname;
                    y_caption = ' '+ $(this).find('SCRTEXT_L').text();
                }
                if (x_axis == elem) x_axis = fieldname;
                if (s_axis == elem) s_axis = fieldname;
            }
        });

        var header = [];
        header.push(s_axis);
        header.push(x_axis);
        header.push(y_axis);

        table_data.push(header);

        $(data).find('output item').each(function () {

            try
            {
                var s = $(this).find(s_axis).text().replace(/&/g, '&amp;');
                var x = $(this).find(x_axis).text().replace(/&/g, '&amp;');
                var y = $(this).find(y_axis).text().replace(/&/g, '&amp;');

                var row = [];
                row.push(s);
                row.push(x);
                row.push(y);

                table_data.push(row);

                properties.value = y;

                if(s_axis != '')
                {
                    if (series_set[s])
                        series_set[s].data.push([x, y]);
                    else
                        series_set[s] = { label: s, data: [[x, y]] };
                }
                else
                {
                    if (series_set[y_axis])
                        series_set[y_axis].data.push([x, y]);
                    else
                        series_set[y_axis] = { label: y_caption, data: [[x, y]] };
                }
            }
            catch(err)
            {
                //Handle errors here
                BOI.BOILib.Util.log(err.toString(),true);
            }
        });
    } //for now get first one

    //Build proper xml
    var chart_data = buildXml(series_set, kpi, x_axis_title);
    $('#table_placeholder').html(buildTable(table_data));

    chart.setData(chart_data);

    chart.addEventListener('pointClick', onChartClick);
    $('#chart_placeholder').empty();
    chart.write('chart_placeholder');
    chart.refresh();
}

function onChartClick(event)
{
    //create drilldown event to open target reprot

    var drilldown = undefined;
    var kpi = properties.kpi;
    var kpiData = properties.data;

    var xAxis = event.data.Name;
    var clickedSeries = event.data.Series.Name;

    //alert('Category: '+ xAxis +'\nSeries: '+clickedSeries);

    //get mappings for source of click.

    var drilldown = undefined;
    if(kpi.SERIES_AXIS != undefined && kpi.SERIES_AXIS != '')
    {
        drilldown = kpi.DRILL_DOWNS[0];

        triggerDrilldown(drilldown, xAxis, clickedSeries, drilldown.TARGET_QUERY);
    }
    else
    {
        for(var drill in kpi.DRILL_DOWNS)
        {
            var drilldown = kpi.DRILL_DOWNS[drill];
            var seriesTechnameNode = $(kpiData).find('META ZBW_QUERY_OUTPUT_METADATA ELEM')
                    .filter(
                    function()
                    {
                        return $(this).text() == drilldown.SOURCE_COLUMN;
                    });

            var seriesNameNode = $(seriesTechnameNode).parent().find('SCRTEXT_L').text();
            if(seriesNameNode == clickedSeries)
            {
                triggerDrilldown(drilldown, xAxis, clickedSeries, drilldown.TARGET_QUERY);
                break;
            }
        }
    }
}

function triggerDrilldown(drilldown, xAxis, seriesValue, targetReportTechname)
{
    BOI.loadReportMeta(undefined, function(report)
    {
        var currentMapping = new Object();
        var vars = new Object();
        for(var currentMappingString in drilldown.MAPPINGS)
        {
            //fill BOI Variable with values from chart based on mappings.
            currentMapping = drilldown.MAPPINGS[currentMappingString];

            //get variable from report
            var currentReportVariable = report.variables[currentMapping.TECHNAME];

            //extra information...
            //we are doing this mapping because the data on the chart cannot be understood by the query
            //each value consist of key, text.
            //text is shown on the chart, the key is in the data (xml).
            //need to lookup for the key to fill the variable with it.

            //if direct value , assing no need for mapping.
            //else lookup in the xml to find the correct node that has the value.
            if(currentMapping.VALUE != '')
                currentReportVariable.value = currentMapping.VALUE;
            else
            {
                //check wether axis or series is mapped to the IO that has the value.
                var lookup = false;
                var nodeValueToLookup = '';
                var nodeToLookup = '';
                if(currentMapping.AXIS == 'x')
                {
                    lookup = true;
                    nodeValueToLookup = xAxis;
                    nodeToLookup = properties.kpi.X_AXIS;
                }
                else if(currentMapping.AXIS == 'series')
                {
                    lookup = true;
                    nodeValueToLookup = seriesValue;
                    nodeToLookup = properties.kpi.SERIES_AXIS;
                }
                //if there is mapping assign the value otherwise leave variable empty.
                if(lookup)
                {
                    //lookup for the value of(axis or series) in the xml data section
                    //after finding the correct value, check the sibling IO to get the mapped value
                    //assign the value to the variable.
                    var lookedUpNode = $(properties.data)
                            .find('OUTPUT item '+ nodeToLookup)
                            .filter(function()
                            {
                                return $(this).text() == nodeValueToLookup;
                            }).parent();

                    currentReportVariable.value = $(lookedUpNode).find(currentMapping.MAPPED_VALUE).text();
                }

            }
        }
        //call BOI open report function and pass BOI variable to it.
        BOI.Events.raiseEvent(BOI.Events.repopen,  [report.id]);
    }, 'Y', targetReportTechname);


}


function buildTable(series_set) {

    var header = "<thead><tr>";
    var rows = "<tbody>";
    var records = [];
    for (var row in series_set) {

        if (row == 0) {
            for (var th in series_set[row])
                header += '<th>' + series_set[row][th] + '</th>';
            header += "</tr></thead>";
        }
        else {
            rows += "<tr>";
            for (var td in series_set[row])
                rows += "<td>" + series_set[row][td] + "</td>";
            rows += "</tr>";
        }
    }

    rows += "</tbody>";

    return '<table>' + header + rows + '</table>';
}
function buildXml(series_set, kpi, x_axis_title) {


    var report_title = properties.current_report.label;
    if(report_title == undefined && properties.current_report.title != undefined)
        report_title = properties.current_report.title;

    var gauges = '<gauges>' +
            '<gauge>' +
            '<chart_settings>' +
            '<chart_background enabled="false" />' +
            '<title enabled="false" />' +
            '</chart_settings>' +
            '<circular>' +
            '<pointers>' +
            '<pointer type="Needle" value="' + properties.value + '" />' +
            '</pointers>' +
            '<axis radius="50" start_angle="90" sweep_angle="180">' +
            '<scale minimum="0" maximum="' + properties.kpi.MAXIMUM + '" major_interval="20" minor_interval="5" />' +
            '<scale_bar enabled="false" />' +
            '<labels enabled="true">' +
            '<font bold="true" />' +
            '<format>{%Value}{numDecimals:0} </format>' +
            '</labels>' +
            '<minor_tickmark enabled="false" />' +
            '<color_ranges>\n{color_ranges}\n</color_ranges>'+
        /*
         '<color_ranges> +
         '<color_range start="0" end="40" color="Green" />' +
         '<color_range start="40" end="80" color="Yellow" />' +
         '<color_range start="80" end="120" color="Red" />' +
         </color_ranges>'*/
            '</axis>' +
            '</circular>' +
            '</gauge>' +
            '</gauges>';

    var colorRangesString = '';
    $.each(kpi.COLOR_RANGES, function(key, value)
    {
        colorRangesString += '<color_range start="'+ this.FROM_VALUE +'" end="'+ this.TO_VALUE +'">' +
                '<fill type="solid" color="#'+ this.COLOR_CODE +'" />'+
                '</color_range>';
    });

    gauges = gauges.replace('{color_ranges}', colorRangesString);


    var charts = '<charts>' +
            '<chart plot_type="' + properties.kpi.PLOT_TYPE + '">' +
            '<data_plot_settings default_series_type="' + properties.kpi.CHART_TYPE + '">' +
            '<pie_series style="Aqua">' +
            '<tooltip_settings enabled="true" />'+
            '<label_settings enabled="true" mode="'+ kpi.LABEL_POSITION +'">'+
            '<background enabled="false" />'+
            '<format>{%Name}{numDecimals:'+ kpi.X_DECIMAL_POSITION +'}</format>'+
            '</label_settings>'+
            '</pie_series>'+
            '</data_plot_settings>' +
            '<chart_settings>' +
            '<chart_background enabled="false" />' +
            '<title enabled="false">' +
            '<text>' + report_title + '</text>' +
            '</title>' +
            '<legend enabled="True" position="bottom" align="center">' +
            '<title enabled="false" />' +
            '</legend>' +
            '<axes>' +
            '<y_axis>' +
            '<title>' +
            '<text>'+ kpi.Y_AXIS_LABEL +'</text>' +
            '</title>' +
            '<scale type="'+ kpi.SCALE_TYPE +'" mode="'+ kpi.SCALE_MODE +'" />' +
            '<labels>' +
            '<format><![CDATA[{%Value}{numDecimals:'+ kpi.Y_DECIMAL_POSITION +'}]]></format>' +
            '</labels>' +
            '</y_axis>' +
            '<x_axis>' +
            '<title>' +
            '<text>'+ kpi.X_AXIS_LABEL +'</text>' +
            '</title>' +
            '<labels>' +
            '<format><![CDATA[{%Value}{numDecimals:'+ kpi.X_DECIMAL_POSITION +'}]]></format>' +
            '</labels>' +
            '</x_axis>' +
            '</axes>' +
            '</chart_settings>' +
            '<data>{data}</data>' +
            '</chart>' +
            '</charts>';

    var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<anychart>' +
            '{charts}' +
            '<margin all="0" />' +
            '{gauges}' +
            '</anychart>';

    if (kpi.PLOT_TYPE == 'Gauge' || kpi.CHART_TYPE == 'Gauge')
        xml = xml.replace('{gauges}', gauges);
    else
        xml = xml.replace('{charts}', charts);

    var data = '';

    for (var i in series_set) {
        var series = '\n<series name="' + series_set[i].label + '">\n{points}\n' +
                '<label>' +
                '<format>{numDecimals:'+ kpi.Y_DECIMAL_POSITION +'}</format>' +
                '</label>' +
                '</series>';
        var points = '';
        for (var p in series_set[i].data)
            points += '<point name="' + series_set[i].data[p][0] + '" y="' + series_set[i].data[p][1] + '">' +
                    '<label>' +
                    '<format>{numDecimals:'+ kpi.X_DECIMAL_POSITION +'}</format>' +
                    '</label>' +
                    '</point>\n';

        data += series.replace('{points}', points);
    }

    return xml.replace('{data}', data);
}
</script>
<!-- COMPONENT STYLING -->
</head>
<body>
<div id="chart_placeholder" class="loading"></div>
<div id="table_placeholder" style="display: none"></div>
</body>
</html>
<%
theme = ''.
%>